package com.itheima.shop.dao;

import com.itheima.shop.utils.ReflectionUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * @author songjun
 * @date 2018/7/17.
 */
public class JdbcDaoImpl<T> implements DAO<T> {
    private QueryRunner queryRunner;
    private Class<T> type;

    public JdbcDaoImpl() {
        queryRunner = new QueryRunner();
        type = ReflectionUtils.getSuperGenericType(getClass());
    }

    @Override
    public int update(Connection connection, String sql, Object... args) throws SQLException {
        return queryRunner.update(connection, sql, args);
    }

    @Override
    public T getOne(Connection connection, String sql, Object... args) throws SQLException {
        return queryRunner.query(connection, sql, new BeanHandler<>(type), args);
    }

    @Override
    public List<T> getList(Connection connection, String sql, Object... args) throws SQLException {
        return queryRunner.query(connection, sql, new BeanListHandler<>(type), args);
    }

    @Override
    public <E> E getForValue(Connection connection, String sql, Object... args) throws SQLException {
        return queryRunner.query(connection, sql, new ScalarHandler<>(), args);
    }

    @Override
    public int[] batch(Connection connection, String sql, Object[]... args) throws SQLException {
        return queryRunner.batch(connection, sql, args);
    }
}
